package com.example.framework

import android.util.Log
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner

class BaseComponent(private val lifecycleOwner: LifecycleOwner) : DefaultLifecycleObserver {

    companion object {
        const val TAG = "BaseComponent"
    }

    var fragment: Fragment? = null

    var activity: FragmentActivity? = null
        get() {
            return field ?: fragment?.activity
        }

    public val isFinish: Boolean get() = activity?.isFinishing ?: true

    init {
        initialize()
    }

    private fun initialize() {
        when (lifecycleOwner) {
            is Fragment -> {
                fragment = lifecycleOwner
                activity = lifecycleOwner.activity
            }

            else -> {
                val msg = "BaseComponent need fragment"
                Log.e(TAG, msg)
//                if (){
//                    throw IllegalArgumentException(msg)
//                }
            }
        }
    }

    private fun getLifecycle(): Lifecycle {
        return lifecycleOwner.lifecycle
    }


    fun attach(): BaseComponent {
        getLifecycle().addObserver(this)
        return this
    }

    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
        getLifecycle().removeObserver(this)
        fragment = null
        activity = null
    }

    /**
     * VM 绑定
     *
     */
    open fun onBind(){}
}